package com.gzcstec.order.service.impl;

import com.gzcstec.order.dataobject.OrderDetail;
import com.gzcstec.order.dataobject.OrderMaster;
import com.gzcstec.order.dto.OrderDTO;
import com.gzcstec.order.enums.ExceptionCodeEnums;
import com.gzcstec.order.enums.OrderStatusEnums;
import com.gzcstec.order.enums.PayStatusEnums;
import com.gzcstec.order.exception.OrderException;
import com.gzcstec.order.repository.OrderDetailRepository;
import com.gzcstec.order.repository.OrderMasterRepository;
import com.gzcstec.order.service.OrderService;
import com.gzcstec.order.utils.KeyUtils;
import com.gzcstec.product.client.ProductClient;
import com.gzcstec.product.dataobject.DecreaseStockInput;
import com.gzcstec.product.dataobject.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private ProductClient productClient;

    /**
     * 1.查询商品信息
     * 2.计算商品总额
     * 3.订单详情进库
     * 4.订单主表进库
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {

         //1.查询商品信息
        //获取购物车的信息
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        //获取购物车商品id
        List<String> productIdList = orderDetailList.stream()
                .map(e -> e.getProductId()).collect(Collectors.toList());
        //获取购物车商品详情列表
        List<ProductInfoOutput> productInfoList = productClient.list(productIdList);

        if(CollectionUtils.isEmpty(productInfoList)) {
            log.error("【订单创建】购物车有误，orderDTO={}" , orderDTO);
            throw new OrderException(ExceptionCodeEnums.CART_ERROR);
        }

        //订单id
        String orderId = KeyUtils.getUniqueKey();

        //遍历购物车
        BigDecimal amount = new BigDecimal(0);
        for(OrderDetail orderDetail : orderDetailList) {

            for(ProductInfoOutput productInfo : productInfoList) {
                if(orderDetail.getProductId().equals(productInfo.getProductId())) {
                    //计算订单总额
                    amount = amount.add(productInfo.getProductPrice()
                            .multiply(new BigDecimal(orderDetail.getProductQuantity())));

                    //订单详情赋值
                    BeanUtils.copyProperties(productInfo , orderDetail);
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtils.getUniqueKey());
                    orderDetail.setCreateTime(null);
                    orderDetail.setUpdateTime(null);
                    //订单详情入库
                    orderDetailRepository.save(orderDetail);
                    break;
                }

            }
        }

        //获取购物车
        List<DecreaseStockInput> cartDTOList = orderDetailList.stream()
                .map(e -> new DecreaseStockInput(e.getProductId() , e.getProductQuantity()))
                .collect(Collectors.toList());

        //减库存
        productClient.decreaseStock(cartDTOList);

        //4.订单主表进库
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO , orderMaster);
        orderMaster.setPayStatus(PayStatusEnums.NEW.getCode());
        orderMaster.setOrderStatus(OrderStatusEnums.NEW.getCode());
        orderMaster.setOrderId(orderId);
        //订单总额
        orderMaster.setOrderAmount(amount);

        orderMasterRepository.save(orderMaster);

        orderDTO.setOrderId(orderMaster.getOrderId());
        return orderDTO;
    }

    @Override
    public OrderDTO finish(String orderId) {
        //1.查询订单
        Optional<OrderMaster> optionalOrderMaster =  orderMasterRepository.findById(orderId);
        if(!optionalOrderMaster.isPresent()) {
            throw new OrderException(ExceptionCodeEnums.ORDER_MASTER_NOT_EXIST);
        }

        //2.判断订单状态
        OrderMaster orderMaster = optionalOrderMaster.get();
        if(orderMaster.getOrderStatus() != OrderStatusEnums.NEW.getCode()) {
            throw new OrderException(ExceptionCodeEnums.ORDER_STATUS_ERROR);
        }

        //3.获取订单详情
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if(CollectionUtils.isEmpty(orderDetailList)) {
            throw new OrderException(ExceptionCodeEnums.ORDER_DETAIL_EMPTY);
        }

        //3.将订单状态更新为完结状态
        orderMaster.setOrderStatus(OrderStatusEnums.OK.getCode());
        orderMasterRepository.save(orderMaster);

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster , orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }
}
